import * as path from "path";
import * as fse from "fs-extra";
import { VIRTUAL_PATH_PREFIX } from "../media";
import { MEDIA_DIR, TEMP_DIR } from "../media/config";

export function isFile(file: string) {
	const exist = fse.existsSync(file);
	if (!exist) {
		return false;
	}
	const stat = fse.statSync(file);
	return stat.isFile();
}

/**
 * 判断是否是 MP3 文件
 */

export const isMP3File = (file: string) =>
	path.extname(file).toUpperCase().includes(".MP3");

/**
 * 判断是否是 MP4 文件
 */

export const isMP4File = (file: string) =>
	path.extname(file).toUpperCase().includes(".MP4");

/**
 * 生成文件储存路径
 */
export function genMP3StorePath(file: string) {
	return path.resolve(MEDIA_DIR, file);
}

/**
 * 生成文件储存路径
 */
export function genMediaTempPath(file: string) {
	return path.resolve(TEMP_DIR, file);
}

/**
 * 初始化文件路径
 * 必须最先执行
 */
export function ensureConfigFiles() {
	fse.ensureDirSync(TEMP_DIR);
	fse.ensureDirSync(MEDIA_DIR);
}

/**
 * 获取真实文件地址
 */
export function resolveFile(virtualPath: string) {
	const fileName = path.basename(virtualPath);
	const actualPath = path.resolve(MEDIA_DIR, fileName);
	return actualPath;
}

export function formatTitle(title: string) {
	title = path.basename(title);
	const index = title.lastIndexOf(".");
	return title.slice(0, index);
}

export function isMP3Buffer(buf: Buffer) {
	if (!buf || buf.length < 3) {
		return false;
	}

	return (
		(buf[0] === 73 && buf[1] === 68 && buf[2] === 51) ||
		(buf[0] === 255 && (buf[1] === 251 || buf[1] === 250))
	);
}

export function isMP4Buffer(buf: Buffer) {
	if (!buf || buf.length < 8) {
		return false;
	}

	return (
		(buf[0] === 0 &&
			buf[1] === 0 &&
			buf[2] === 0 &&
			buf[3] === 24 &&
			buf[4] === 102 &&
			buf[5] === 116 &&
			buf[6] === 121 &&
			buf[7] === 112) ||
		(buf[0] === 51 && buf[1] === 103 && buf[2] === 112 && buf[3] === 53)
	);
}

export function genVirtualPath(file: string) {
	const virtualPath = path.join(VIRTUAL_PATH_PREFIX, path.basename(file));
	return virtualPath;
}

export function setCopyName(file: string) {
	const { ext, name } = splitFilename(file);
	const copytime = new Date().getTime();
	return `${name}_cpt${copytime}${ext}`;
}

export function splitFilename(file: string) {
	const index = file.lastIndexOf(".");

	const ext = file.slice(index);
	const name = file.slice(0, index);
	return {
		ext,
		name,
	};
}

export function genTempChunkDir(file: string, uid?: string) {
	const index = file.indexOf(".");
	let name = file.slice(0, index);
	if (uid) {
		name += "-" + uid;
	}
	return path.resolve(TEMP_DIR, name);
}

export function safeRemoveDir(dir: string, keepDir = false) {
	const exist = fse.existsSync(dir);

	if (exist) {
		fse.emptyDirSync(dir);
		if (!keepDir) {
			fse.rmdirSync(dir);
		}
	}
}
